<template>
  <div>
    <div style="margin-bottom: 5px;">
      <el-input
          v-model="query.name"
          placeholder="请输入名字"
          style="width: 200px;"
          @keyup.enter.native="getList"
          clearable>
      </el-input>
      <el-select v-model="query.sex" placeholder="请选择" style="margin-left: 10px;">
        <el-option
            v-for="item in sexs"
            :key="item.value"
            :label="item.label"
            :value="item.value">
        </el-option>
      </el-select>
      <el-button type="primary" style="margin-left: 10px;" @click="getList()">查询</el-button>
      <el-button type="success" @click="resParams">重置</el-button>
      <el-button type="success" @click="add()">添加</el-button>
    </div>
  <el-table
      :data="tableData"
      :header-cell-style="{ background: '#f3f6fd', color: '#555' }"
  >
    <el-table-column prop="id" label="编号" width="80">
    </el-table-column>
    <el-table-column prop="no" label="账号" width="120">
    </el-table-column>
    <el-table-column prop="name" label="姓名" width="120">
    </el-table-column>
    <el-table-column prop="age" label="年龄" width="100">
    </el-table-column>
    <el-table-column prop="sex" label="性别" width="120">
      <template slot-scope="scope">
        <el-tag
            :type="scope.row.sex === 1 ? 'primary' : 'success'"
            disable-transitions>{{scope.row.sex === 1 ? '男' : '女'}}</el-tag>
      </template>
    </el-table-column>
    <el-table-column prop="phone" label="手机号" width="120">
    </el-table-column>
    <el-table-column prop="roleId" label="角色" width="120">
      <template slot-scope="scope">
        <el-tag
            :type="scope.row.roleId === 0 ? 'danger' : (scope.row.roleId === 1 ? 'primary' : 'success')"
            disable-transitions>{{scope.row.roleId === 0 ? '超级管理员' :
                                        (scope.row.roleId === 1 ? '普通管理员' : '用户')}}</el-tag>
      </template>
    </el-table-column>
    <el-table-column prop="operate" label="操作">
      <template slot-scope="scope">
      <el-button size="small" type="success" @click="update(scope.row)">编辑</el-button>
      <el-button size="small" type="danger" @click="del(scope.row)">删除</el-button>
      </template>
    </el-table-column>
  </el-table>
    <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="this.query.page"
        :page-sizes="[5, 10, 20, 30]"
        :page-size="this.query.size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="this.total">
    </el-pagination>

<!--    添加 （from表单）-->
    <el-dialog title="添加新成员"
               :visible.sync="dialogFormVisible"
               :before-close="handleClose"
    >
      <el-form :model="form" :rules="rules" ref="form" >
        <el-form-item label="账号" :label-width="formLabelWidth" prop="no">
          <el-col :span="20">
            <el-input
                v-model="form.no"
                placeholder="请输入账号"
                autocomplete="off"
                clearable
            >
            </el-input>
          </el-col>
        </el-form-item>
        <el-form-item label="姓名" :label-width="formLabelWidth" prop="name">
          <el-col :span="20">
            <el-input
                v-model="form.name"
                placeholder="请输入名字"
                autocomplete="off"
                clearable
            >
            </el-input>
          </el-col>
        </el-form-item>
          <el-form-item label="密码" :label-width="formLabelWidth" prop="password">
            <el-col :span="20">
              <el-input
                  v-model="form.password"
                  placeholder="请输入密码"
                  autocomplete="off"
                  clearable
              >
              </el-input>
            </el-col>
          </el-form-item>
        <el-form-item label="年龄" :label-width="formLabelWidth" prop="age">
          <el-col :span="20">
            <el-input
                v-model="form.age"
                placeholder="请输入年龄"
                autocomplete="off"
                clearable
            >
            </el-input>
          </el-col>
        </el-form-item>
        <el-form-item label="性别" :label-width="formLabelWidth" prop="sex">
          <el-radio-group v-model="form.sex">
            <el-radio label="1">男</el-radio>
            <el-radio label="0">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="手机号" :label-width="formLabelWidth" prop="phone">
          <el-col :span="20">
            <el-input
                v-model="form.phone"
                placeholder="请输入手机号"
                autocomplete="off"
                clearable
            >
            </el-input>
          </el-col>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="save()">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "Main",
  data() {
    //判断年龄是不能超过150岁的
    let checkAge = (rule, value, callback) => {
      if(value>150){
        callback(new Error('年龄输入过大'));
      }else{
        callback();
      }
    };
    let checkDuplicate =(rule,value,callback)=>{
      if(this.form.id){
        return callback();
      }
      this.axios.get(this.$httpUrl+"/user/findByNo?no="+this.form.no).then(res=>res.data).then(res=>{
        console.log(res)
        let data= res.content;
        if(data != null){
          callback(new Error('账号已经存在'));
        }else {
          callback()
        }

      })
    };

    const item = {
      date: '2016-05-02',
      name: '王小虎',
      address: '上海市普陀区金沙江路 1518 弄'
    };
    return {
      tableData: [],
      query:{
        page:1, //这个设置小一点不然会跑到第二页去的
        size:5,
        name:'',
        sex:''
      },
      total:0,
      sexs:[
        {
          value: '1',
          label: '男'
        },
        {
          value: '0',
          label: '女'
        }
      ],
      dialogFormVisible:false,
      form:{
           id:'',
           no:'',
           name:'',
           password:'',
           age:'',
           sex:'1',
           phone:'',
           roleId:'1',
      },
      formLabelWidth:'120px',
      rules: {
        no: [
          {required: true, message: '请输入账号', trigger: 'blur'},
          {min: 3, max: 8, message: '长度在 3 到 8 个字符', trigger: 'blur'},
          {validator:checkDuplicate,trigger: 'blur'}
        ],
        name: [
          {required: true, message: '请输入姓名', trigger: 'blur'}
        ],
        password: [
          {required: true, message: '请输入密码', trigger: 'blur'},
          {min: 3, max: 8, message: '长度在 3 到 8 个字符', trigger: 'blur'}
        ],
        age: [
          {required: true, message: '请输入年龄', trigger: 'blur'},
          {min: 1, max: 3, message: '长度在 1 到 3 个位', trigger: 'blur'},
          {pattern: /^([1-9][0-9]*){1,3}$/,message: '年龄必须为正整数字',trigger: "blur"},
          {validator:checkAge,trigger: 'blur'}
        ],
        phone: [
          {required: true,message: "手机号不能为空",trigger: "blur"},
          {pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/, message: "请输入正确的手机号码", trigger: "blur"}
        ]
      }

    }
  },
  mounted() {
    this.getList();
  },
  methods:{
      getList(){
        this.axios.get(this.$httpUrl+'/user/getList',{
          params:{
            page:this.query.page,
            size:this.query.size,
            name:this.query.name,
            sex:this.query.sex
          }
        }).then(resp=>resp.data).then(
            (resp)=>{
              console.log(resp)
              this.tableData=resp.content.list
              this.total=resp.content.total
            }
        )
      },
    save(){
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.axios.post(this.$httpUrl+'/user/saveOrUpdate',this.form).then(resp=>resp.data).then(
              (resp)=>{
                let data=resp.success;
                if(data){
                  this.$message({
                    message: resp.message,
                    type: 'success'
                  });
                  this.getList()
                  this.dialogFormVisible=false
                }
              }
          )
        } else {
          console.log('请输入正确的信息');
          return false;
        }
      });

    },
    del(row){
        let id=row.id;

        this.$confirm('是否删除','操作',{confirmButtonText: '确定',cancelButtonText: '取消',type: 'warning'})
            .then(()=>{
              // 确定按钮回调
              // this.$message.success('删除了')
              // ajax操作
              this.axios.delete(this.$httpUrl+'/user/delete/'+id).then( (resp) =>{
                console.log(resp);
                let data=resp.data
                if(data.success){
                  this.$message({
                    message: data.message,
                    type: 'success'
                  });
                  this.getList()
                }
              })
            })
            .catch(()=>{
              // 取消按钮回调
              this.$message.error('取消了')
            })
    },
    update(row){ //修改是有问题的，后面在来处理一下
        this.dialogFormVisible=true,
            this.form.no=row.no,
            this.form.name=row.name,
            this.form.password=row.password,
            this.form.age=row.age,
            this.form.sex=row.sex+'',
            this.form.phone=row.phone
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.query.size=val
      this.getList()
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.query.page=val
      this.getList()
    },
    resParams(){
        this.query.name=""
        this.query.sex=""
    },
    add(){
          this.form={}
          this.dialogFormVisible=true
    },
    handleClose(done) {
      this.$confirm('确认关闭？')
          .then(_ => {
            done();
          })
          .catch(_ => {});
    },

  }
}
</script>

<style scoped>

</style>